package top.kaoshanji.p1ch01a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 代码清单-p1ch01a-8页a：ServletConfigDemoServlet类
 * URL访问地址：/servletConfigDemo
 * author kaoshanji
 * ^_^
 * create time 2025/4/7 09:38
 */
@WebServlet(name = "ServletConfigDemoServlet", urlPatterns = {"/servletConfigDemo"}, initParams = {
        @WebInitParam(name = "admin", value = "kao"),
        @WebInitParam(name = "email", value = "admin@xxx.com")
})
public class ServletConfigDemoServlet implements Servlet {

    // 实例属性
    private transient ServletConfig servletConfig;

    // 初始化方法
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.servletConfig = config;
    }

    // 访问方法
    @Override
    public ServletConfig getServletConfig() {
        return servletConfig;
    }

    // 业务方法
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        // 设置响应对象的编码和内容格式
        res.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = res.getWriter();

        ServletConfig servletConfig1 = getServletConfig();
        String admin = servletConfig1.getInitParameter("admin");
        String email = servletConfig1.getInitParameter("email");

        out.print("<html><head></head><body>" +
                "Admin:" + admin +
                "<br/>Email:" + email +
                "</body></html>");

    }

    @Override
    public String getServletInfo() {
        return "ServletConfig Demo";
    }

    @Override
    public void destroy() {

    }

}
